import 'package:kkhousekeep/models/home_bill_details_entity.dart';
import 'package:kkhousekeep/models/home_bill_years_entity.dart';
import 'package:kkhousekeep/net/base_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/page/home/convenient/bill/bill_page_controller.dart';

import '../models/home_bill_list_entity.dart';
import '../tools/dialog_util.dart';
import 'api.dart';

class BillConnect extends BaseConnect {
  Future<List<HomeBillListObj>> getBillList({
    required String year,
  }) async {
    var response = await get(Api.getBillList, query: {'year': year});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeBillListEntity entity = HomeBillListEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj);
    }
    return Future.value([]);
  }

  Future<HomeBillDetailsObj> getBillDetails({
    required int year,
    required int month,
  }) async {
    var response = await get(Api.getBillDetailList, query: {
      'year': year.toString(),
      'month': month.toString(),
    });
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value(
        HomeBillDetailsObj().copyWith(
          address: '',
          items: [],
        ),
      );
    }
    HomeBillDetailsEntity entity =
        HomeBillDetailsEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj);
    }
    return Future.value(
      HomeBillDetailsObj().copyWith(
        address: '',
        items: [],
      ),
    );
  }

  Future<List<String>> getBillYears() async {
    var unit = BillPageController.unitYear;

    var response = await get(Api.getBillYearList);
    if (response.body == null) {
      DialogUtil.showNetworkError();
      int year = DateTime.now().year;
      return Future.value([year.toString()]);
    }
    HomeBillYearsEntity entity = HomeBillYearsEntity.fromJson(response.body);

    if (ResponseCode.success == entity.code && entity.obj.isNotEmpty) {
      var dataList = entity.obj.map((e) => '$e$unit').toList();
      return Future.value(dataList);
    }

    int year = DateTime.now().year;
    return Future.value([year.toString()]);
  }
}
